import React, { useReducer, useEffect } from "react";
import "./cate.css"
import { Icon, } from 'antd-mobile';
import { initState, reducer, actions } from "./cate";
import { reqGetcate, reqGetgoods, reqCartadd } from "../../request/api"
const Case = (props) => {
  const [state, dispatch] = useReducer(reducer, initState);
  let { cates, goods } = state
  //进来页面
  useEffect(() => {
    // 商品分类
    reqGetcate().then(res => {
      if (res.data.code === 200) {
        dispatch(actions.changeCates(res.data.list))
      }
    })
    // 分类商品
    reqGetgoods(1).then(res => {
      if (res.data.code === 200) {
        dispatch(actions.changeGoods(res.data.list))
      }
    })
    
  }, []);
  let getGoods = (id) => {
    // 分类商品
    reqGetgoods({ fid: id }).then(res => {
      if (res.data.code === 200) {
        dispatch(actions.changeGoods(res.data.list))
      }
    })
  }
  let cartAdd=(id)=>{
    // 加购
    reqCartadd({ uid: JSON.parse(sessionStorage.getItem("user")).uid, type: 1, goodsid: id, num: 1 })
  }
  return (
    <div className="pad">
      <div className="cate_search clearfix">
        <Icon type="search" className="fl" />
        <input type="text" placeholder="按内容搜索" className="fl" />
      </div>
      <div className="cate_content1">
        <ul className="side">
          {
            cates ? cates.map(item => (
              <li key={item.id} onClick={() => getGoods(item.id)}>{item.catename}</li>
            )) : null
          }
        </ul>

        <div className="cate_content2">
          {
            goods ? goods.map(item => (
              <div className="clearfix" key={item.id}>
                <img src={item.img} alt="" className="fl" />
                <ul className="fr">
                  <li>{item.goodsname}</li>
                  <li>
                    <span>￥{item.price}</span>
                    <span>￥{item.market_price}</span><br />
                    <span>限购{item.islimit}份</span>
                  </li>
                  <li>
                    {item.description}
                  </li>
                </ul>
                <button onClick={() => cartAdd(item.id)}>加购</button>
              </div>
            )) : null
          }

        </div>
      </div>
    </div>
  );
};

export default Case;
